use log::info;
use tokio::sync::mpsc;
use tokio::sync::mpsc::{UnboundedSender};
use rpc::dto::{RpcHeader};
use rpc::{send, ChannelId, RpcResult};
use rpc::connection_manager::event::WriteData;
use rpc::station::output_station::{OutputEvent, OutputStation};
use crate::connection_manager::message::ConnectionMessage;

pub fn start_output_station(stream_sender: UnboundedSender<ConnectionMessage>) -> UnboundedSender<OutputStationMessage> {
    let (sender, receiver) = mpsc::unbounded_channel();

    tokio::spawn(async move {
        let output_manager: OutputStation<OutputStationMessage, ConnectionMessage> = OutputStation::new(stream_sender);
        output_manager.run(receiver)
    });

    sender

}

pub enum OutputStationMessage {
    OutputData { header: RpcHeader, data: Vec<u8>, has_response: bool},
}

impl OutputEvent<OutputStationMessage, ConnectionMessage> for OutputStationMessage {
    fn handle(self, manager: &mut OutputStation<OutputStationMessage, ConnectionMessage>) -> RpcResult<()> {
        match self {
            OutputStationMessage::OutputData { header, data, has_response } => {
                let local_seq = header.local_seq().unwrap();
                if has_response { // 输出对象需要远程答复
                    let senders = manager.stream_sender.clone();
                    let write_data = WriteData::new(ChannelId::new(0), local_seq, data, true, None);
                    let data_t = ConnectionMessage::Write(write_data);

                    // let m = OutputStationMessage::OutputData { rpc_data_byte, has_response };
                    // manager.data_map.entry(local_seq.to_string()).or_insert(m);

                    if !send(&senders, data_t) {
                        info!("send sender error");
                    }
                    Ok(())
                } else {  // 输出对象不需要远程答复
                    let senders = manager.stream_sender.clone();
                    let write_data = WriteData::new(ChannelId::new(0), local_seq, data, true, None);
                    let data_t = ConnectionMessage::Write(write_data);
                    if !send(&senders, data_t) {
                        info!("send sender error");
                    }
                    Ok(())
                }
            }
        }
    }
}